package me.sdevil507.supports.shiro.realm;

import me.sdevil507.org.po.OrgUserPo;
import me.sdevil507.org.service.OrgRoleService;
import me.sdevil507.org.service.OrgUserService;
import me.sdevil507.supports.shiro.enums.LoginChannel;
import me.sdevil507.supports.shiro.enums.LoginModeType;
import me.sdevil507.supports.shiro.enums.RoleType;
import me.sdevil507.supports.shiro.helper.OrgAccountHelper;
import me.sdevil507.supports.shiro.realms.BaseAuthorizingRealm;
import me.sdevil507.supports.shiro.token.SmsToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * 短信登录验证域
 *
 * @author sdevil507
 * created on 2020/8/6
 */
public class OrgSmsRealm extends BaseAuthorizingRealm {

    @Autowired
    private OrgRoleService orgRoleService;

    @Autowired
    private OrgUserService orgUserService;

    /**
     * 定义realm名称
     *
     * @return realm名称
     */
    @Override
    public String getName() {
        return LoginChannel.ORG.name() + ":" + LoginModeType.SMS.name();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof SmsToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setStringPermissions(orgRoleService.findPermissions());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取登录用户手机号
        String phoneNumber = (String) token.getPrincipal();
        OrgUserPo orgUserPo = orgUserService.readOneByPhoneNumber(phoneNumber);

        // 用户名不存在
        if (orgUserPo == null) {
            throw new UnknownAccountException();
        }

        // 如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(orgUserPo.getPhoneNumber(),
                "",
                getName()
        );
    }
}
